package com.szlanyou.lylog.tool;

import android.content.Context;

import com.szlanyou.test.LyLog;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Aivin
 * so 的路径在 \app\build\intermediates\cmake\debug\obj\armeabi-v7a\liblyEnciphereddata.so
 */
public class LyLogSaveTool {
    /**
     * 单线程的线程池
     */
    private final ExecutorService recordExecutor = Executors.newSingleThreadExecutor();
    private final AtomicBoolean initFlag = new AtomicBoolean(false);
    /**
     * 当前的日志文件。
     * 如果文件已达到最大限制，会开辟一个新的文件（文件名字会变）。
     */
    private File logFile;

    public static LyLogSaveTool getInstance() {
        return SingletonFactory.INSTANCE;
    }

    private static class SingletonFactory {
        private static final LyLogSaveTool INSTANCE = new LyLogSaveTool();
    }


    /**
     * 异步初始化
     */
    public void initAsyn(Context context) {
        if (initFlag.get()) {
            LyLog.showErrorLog("已经初始化了，无需重复操作");
            return;
        }
        recordExecutor.execute(() -> init(context));
    }

    private void init(Context context) {
        String logFileDir = LyAppTool.getLogFileDir(context).getAbsolutePath();
        LyLog.showLog("开始初始化日志保存工具, dir="+logFileDir);
        File baseDir = new File(logFileDir);
        if (!baseDir.exists()) {
            boolean mkResult = baseDir.mkdirs();
            LyLog.showLog("日志目录不存在，重新创建。结果=" + mkResult + "  " + baseDir);
        }


        String logFileAbsolutePath = nativeInit(logFileDir);
        logFile = new File(logFileAbsolutePath);
        LyLog.showLog("日志工具初始化结束，结果=" + logFileAbsolutePath+" 当前文件大小="+logFile.length());
        initFlag.set(true);
    }


    public void writeLogAsyn(final String msg) {
        if (!initFlag.get()) {
            LyLog.showErrorLog("请先初始化");
            return;
        }

        if (!LyAppTool.isLogFileExist(logFile)) {
            LyLog.showErrorLog("文件不存在 " + logFile.getAbsolutePath());
            return;
        }

        //recordExecutor.execute(() -> {
            String msgContent = msg + "\n";
            boolean result = nativeWrite(msgContent);
            if (!result) {
                LyLog.showErrorLog("日志保存失败。" + msgContent);
            }else {
                LyLog.showLog("保存成功。当前文件大小="+logFile.length()+"  "+msg);
            }
        //});
    }

    static {
        System.loadLibrary("lyLogSave");
    }

    /**
     * @param dir 日志文件目录
     * @return 日志文件路径
     */
    private native String nativeInit(String dir);

    private native boolean nativeWrite(String msgContent);
}
